-- ========================================================================
-- Northwind database example queries
-- ========================================================================
-- Northwind is a fully relational CoraDB database (no graph objects), so
-- these are standard ANSI SQL queries using JOINs, aggregates, a
-- self-join on the employee reports-to chain, and the database's views.
-- Identifiers use snake_case, so bracket-quoted names such
-- as [order_details] and [order_id] are used throughout.
-- ========================================================================

------------------------------------------------------------------------
-- Catalogue: products, categories, suppliers
------------------------------------------------------------------------

-- All products in the "Beverages" category, cheapest first.
SELECT p.[product_name], p.[unit_price], p.[units_in_stock]
FROM [products] p
INNER JOIN [categories] c ON p.[category_id] = c.[category_id]
WHERE c.[category_name] = 'Beverages'
ORDER BY p.[unit_price];

-- How many products does each category hold, and their average price?
SELECT c.[category_name], COUNT(*) AS [products], ROUND(AVG(p.[unit_price]), 2) AS [avg_price]
FROM [categories] c
INNER JOIN [products] p ON c.[category_id] = p.[category_id]
GROUP BY c.[category_name]
ORDER BY [products] DESC;

-- The 10 most expensive products with their supplier.
SELECT p.[product_name], s.[company_name] AS [supplier], p.[unit_price]
FROM [products] p
INNER JOIN [suppliers] s ON p.[supplier_id] = s.[supplier_id]
ORDER BY p.[unit_price] DESC
LIMIT 10;

-- Which suppliers provide the most products?
SELECT s.[company_name], COUNT(*) AS [products]
FROM [suppliers] s
INNER JOIN [products] p ON s.[supplier_id] = p.[supplier_id]
GROUP BY s.[company_name]
ORDER BY [products] DESC
LIMIT 10;

-- Products at or below their reorder level (need restocking, still active).
SELECT p.[product_name], p.[units_in_stock], p.[reorder_level]
FROM [products] p
WHERE p.[discontinued] = 0 AND p.[units_in_stock] <= p.[reorder_level]
ORDER BY p.[units_in_stock];

------------------------------------------------------------------------
-- Customers and geography
------------------------------------------------------------------------

-- All customers in Germany.
SELECT c.[company_name], c.[contact_name], c.[city]
FROM [customers] c
WHERE c.[country] = 'Germany'
ORDER BY c.[city];

-- How many customers are there per country? (top 10)
SELECT c.[country], COUNT(*) AS [customers]
FROM [customers] c
GROUP BY c.[country]
ORDER BY [customers] DESC
LIMIT 10;

-- Customers who have never placed an order.
SELECT c.[customer_id], c.[company_name]
FROM [customers] c
WHERE NOT EXISTS (SELECT 1 FROM [orders] o WHERE o.[customer_id] = c.[customer_id])
ORDER BY c.[company_name];

------------------------------------------------------------------------
-- Sales analytics
------------------------------------------------------------------------

-- Top 10 customers by total order value.
SELECT c.[company_name], ROUND(SUM(od.[unit_price] * od.[quantity] * (1 - od.[discount])), 2) AS [total_spent]
FROM [customers] c
INNER JOIN [orders] o ON c.[customer_id] = o.[customer_id]
INNER JOIN [order_details] od ON o.[order_id] = od.[order_id]
GROUP BY c.[company_name]
ORDER BY [total_spent] DESC
LIMIT 10;

-- Total revenue by product category.
SELECT c.[category_name], ROUND(SUM(od.[unit_price] * od.[quantity] * (1 - od.[discount])), 2) AS [revenue]
FROM [categories] c
INNER JOIN [products] p ON c.[category_id] = p.[category_id]
INNER JOIN [order_details] od ON p.[product_id] = od.[product_id]
GROUP BY c.[category_name]
ORDER BY [revenue] DESC;

-- Revenue generated by each employee (sales rep).
SELECT e.[first_name] || ' ' || e.[last_name] AS [employee],
       ROUND(SUM(od.[unit_price] * od.[quantity] * (1 - od.[discount])), 2) AS [revenue]
FROM [employees] e
INNER JOIN [orders] o ON e.[employee_id] = o.[employee_id]
INNER JOIN [order_details] od ON o.[order_id] = od.[order_id]
GROUP BY e.[employee_id], e.[first_name], e.[last_name]
ORDER BY [revenue] DESC;

-- The 10 best-selling products by units sold.
SELECT p.[product_name], SUM(od.[quantity]) AS [units_sold]
FROM [products] p
INNER JOIN [order_details] od ON p.[product_id] = od.[product_id]
GROUP BY p.[product_name]
ORDER BY [units_sold] DESC
LIMIT 10;

-- Number of orders and revenue per year. (Use YEAR()/TO_CHAR() on dates: SUBSTRING()
-- on a DATE works on its default text form 'MM/DD/YYYY', not 'YYYY-MM-DD'.)
SELECT YEAR(o.[order_date]) AS `year`,
       COUNT(DISTINCT o.[order_id]) AS [orders],
       ROUND(SUM(od.[unit_price] * od.[quantity] * (1 - od.[discount])), 2) AS [revenue]
FROM [orders] o
INNER JOIN [order_details] od ON o.[order_id] = od.[order_id]
GROUP BY YEAR(o.[order_date])
ORDER BY `year`;

-- Orders handled by each shipper, with total freight.
SELECT s.[company_name] AS [shipper], COUNT(*) AS [orders], ROUND(SUM(o.[freight]), 2) AS [total_freight]
FROM [shippers] s
INNER JOIN [orders] o ON s.[shipper_id] = o.[shipper_id]
GROUP BY s.[company_name]
ORDER BY [orders] DESC;

-- Average order value (order total across all lines).
SELECT ROUND(AVG(t.[order_total]), 2) AS [avg_order_value]
FROM (SELECT od.[order_id] AS [order_id],
             SUM(od.[unit_price] * od.[quantity] * (1 - od.[discount])) AS [order_total]
      FROM [order_details] od
      GROUP BY od.[order_id]) t;

-- Total freight billed per destination country. (top 10)
SELECT o.[ship_country], ROUND(SUM(o.[freight]), 2) AS [total_freight]
FROM [orders] o
GROUP BY o.[ship_country]
ORDER BY [total_freight] DESC
LIMIT 10;

------------------------------------------------------------------------
-- Employees and the management chain
------------------------------------------------------------------------

-- Each employee and the manager they report to (self-join on ReportsTo).
SELECT e.[first_name] || ' ' || e.[last_name] AS [employee],
       m.[first_name] || ' ' || m.[last_name] AS [manager]
FROM [employees] e
LEFT JOIN [employees] m ON e.[reports_to] = m.[employee_id]
ORDER BY [manager], [employee];

-- How many people report directly to each manager?
SELECT m.[first_name] || ' ' || m.[last_name] AS [manager], COUNT(*) AS [direct_reports]
FROM [employees] e
INNER JOIN [employees] m ON e.[reports_to] = m.[employee_id]
GROUP BY m.[employee_id], m.[first_name], m.[last_name]
ORDER BY [direct_reports] DESC;

-- How many employees were hired each year?
SELECT YEAR(e.[hire_date]) AS [hire_year], COUNT(*) AS [hired]
FROM [employees] e
GROUP BY YEAR(e.[hire_date])
ORDER BY [hire_year];

------------------------------------------------------------------------
-- Territories and regions
------------------------------------------------------------------------

-- Number of territories in each region.
SELECT r.[region_description] AS [region], COUNT(*) AS [territories]
FROM [region] r
INNER JOIN [territories] t ON r.[region_id] = t.[region_id]
GROUP BY r.[region_description]
ORDER BY [territories] DESC;

-- How many territories does each employee cover? (top 10)
SELECT e.[first_name] || ' ' || e.[last_name] AS [employee], COUNT(*) AS [territories]
FROM [employees] e
INNER JOIN [employee_territories] et ON e.[employee_id] = et.[employee_id]
GROUP BY e.[employee_id], e.[first_name], e.[last_name]
ORDER BY [territories] DESC
LIMIT 10;

-- Employees assigned to territories in the "Western" region.
SELECT DISTINCT e.[first_name] || ' ' || e.[last_name] AS [employee], t.[territory_description] AS [territory]
FROM [employees] e
INNER JOIN [employee_territories] et ON e.[employee_id] = et.[employee_id]
INNER JOIN [territories] t ON et.[territory_id] = t.[territory_id]
INNER JOIN [region] r ON t.[region_id] = r.[region_id]
WHERE r.[region_description] = 'Western'
ORDER BY [employee], [territory];

------------------------------------------------------------------------
-- Using the database views
------------------------------------------------------------------------

-- The 10 largest orders by subtotal (view: Order Subtotals).
SELECT [order_id], ROUND([subtotal], 2) AS [subtotal]
FROM [order_subtotals]
ORDER BY [subtotal] DESC
LIMIT 10;

-- Category sales for 1997 (view: Category Sales for 1997).
SELECT [category_name], ROUND([category_sales], 2) AS [category_sales]
FROM [category_sales_for_1997]
ORDER BY [category_sales] DESC;

-- Products priced above the catalogue average (view: Products Above Average Price).
SELECT [product_name], [unit_price]
FROM [products_above_average_price];

-- The current (non-discontinued) product list (view: Current Product List).
SELECT [product_id], [product_name]
FROM [current_product_list]
LIMIT 15;


